package com.xiaoyu.izf.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.xiaoyu.izf.config.SysConfig;
import com.xiaoyu.izf.event.WithdrawApplyEvent;
import com.xiaoyu.izf.model.UserCardInfo;
import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.model.exception.BusinessException;
import com.xiaoyu.izf.model.exception.BusinessStatusEnum;
import com.xiaoyu.izf.repository.UserCardInfoDao;
import com.xiaoyu.izf.repository.UserInfoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.Max;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Service
public class UserInfoService {
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private UserCardInfoDao userCardInfoDao;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private CommissionGetLogService commissionGetLogService;


    public UserInfo findByUserName(String userName){
        return  userInfoDao.findByUserName(userName);
    }

    public UserInfo userInfoAdd(String userName,String nickName, String pwd, UserInfo pushUser){
        String token = IdUtil.simpleUUID();
        UserInfo user = new UserInfo();
        user.setUserName(userName);
        pwd = SecureUtil.md5(pwd+ SysConfig.pwdEx);
        user.setPwd(pwd);
        user.setHeadImgUrl("pic/head.png");
        String nick = userName.substring(0,3)+"****"+userName.substring(7);
        user.setNickName(nickName);
        user.setToken(token);
        user.setPushCode(pushCodeGet());
        if(pushUser==null){
            user.setPushUid(0);
            user.setGradePushUid(0);
        }else{
            user.setPushUid(pushUser.getId());
            user.setGradePushUid(pushUser.getPushUid());
        }
        user.setVipType(0);
        user.setCommission(0);
        user.setCommissionDeposit(0);
        user.setCommissionPaid(0);
        user.setCommissionPaying(0);
        user.setRegTime(new Timestamp(System.currentTimeMillis()));
        user.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
        user.setIsDel(0);
        user.setIsAdmin(0);
        //int n = regUserCount(DateUtil.format(DateUtil.date(),"yyyy-MM"))+1;
        //String osn = DateUtil.format(DateUtil.date(),"yyyyMM")+NumberUtil.decimalFormat("000",n);
        String osn = "粉丝";
        user.setOfficialServiceNumber(osn);
        user.setIsTest(0);
        user.setToTheAccount(0);
        user.setRegionCode("");
        user.setSource(0);
        user = userInfoDao.save(user);
        return user;
    }

    public UserInfo userSave(UserInfo user){
        return userInfoDao.save(user);
    }

    public UserCardInfo userCardOne(int uid){
        UserCardInfo card = userCardInfoDao.findOneById(uid);
        if(card==null){
            card = new UserCardInfo();
            card.setBankAccount("");
            card.setBankBranchName("");
            card.setBankName("");
            card.setId(uid);
            card.setUserName("");
            userCardInfoDao.save(card);
        }
        return card;
    }

    public UserCardInfo userCardSave(UserCardInfo card){
        return userCardInfoDao.save(card);
    }

    public UserCardInfo userCardAdd(int uid, String userName, String accout, String bankName, String bankBranchName){
        UserCardInfo card = userCardOne(uid);
        card.setBankAccount(accout);
        card.setBankBranchName(bankBranchName);
        card.setBankName(bankName);
        card.setId(uid);
        card.setUserName(userName);
        return userCardSave(card);
    }

    public UserInfo userInfoByToken(String token){
        return  userInfoDao.findByToken(token);
    }

    public UserInfo userInfoByPushCode(String pushCode){
        return userInfoDao.findByPushCode(pushCode);
    }

    public String pushCodeGet(){
        String pushCode = "";
        UserInfo userInfo = null;
        while (true){
            pushCode = RandomUtil.randomNumbers(7);
            userInfo = userInfoDao.findByPushCode(pushCode);
            if(userInfo==null){
                break;
            }
        }
        return pushCode;
    }

    public UserInfo userInfo(int id){
        return  userInfoDao.findById(id);
    }

    @Transactional
    public boolean applyWithdraw(UserInfo user, int moneyApply){
        //TODO 金额待定
        //int min = 1;//支持的最小提现金额
        if (moneyApply>user.getCommissionDeposit()){
            throw new BusinessException(BusinessStatusEnum.ERROR,"可提余额不足");
        }
        if(moneyApply<100){
            throw new BusinessException(BusinessStatusEnum.ERROR,"提现必须大于1元");
        }
        user.setCommissionPaying(user.getCommissionPaying() + moneyApply);
        user.setCommissionDeposit(user.getCommissionDeposit()-moneyApply);
        user = userSave(user);

        //发布提现申请事件
        //applicationContext.publishEvent(new WithdrawApplyEvent(user));
        commissionGetLogService.add(user.getId(),moneyApply);
        return true;
    }


    public List<UserInfo> pushUserList(int uid){
        return userInfoDao.findAllByPushUid(uid);
    }

    public int regUserCount(String date){
        Integer n = jdbcTemplate.queryForObject("select count(*) from user_info where DATE_FORMAT(reg_time,'%Y-%m')='"+date+"' and vip_type>0",Integer.class);
        return n;
    }

    public UserInfo findByOSN(String osn){
        return userInfoDao.findByOfficialServiceNumber(osn);
    }
}
